// 1.导入核心库
import React,{Component} from "react";
import '../../style/index.scss'
 
class DemoComment extends Component {
  state = { 
    title:'',
    content:'',
    list:[
      {
        title:'jack',
        content: ' 沙发！！！'
      },
      {
        title:'rose',
        content: ' 板凳~'
      },
      {
        title:'tom',
        content: ' 楼主好人'
      }
    ]     
}
//获取input输入的值
updateTitle = (e) =>{
  //从事对象event中拿到input的值来更新state
  let title = e.target.value
  console.log(e);
  this.setState({
    title
  })
} 
//获取文本域中输入的值
updateContent = (e) =>{
  //从事件对象event中拿到input的值来更新state
  console.log(e);
  this.setState({
    content:e.target.value
  })
}

comments = () =>{
  console.log(this.state);
  //组装数据格式/更新list数据
  const {title,content} = this.state
  //第一种方法:用Es6解构方法生成一个新数组，push新数组，再更新list
  // let newArr = [...this.state.list]
  //     newArr.push({title,content})
      // this.setState({
      //     list:newArr
      // })
  // 第二种方法
  let newArr = this.state.list.concat([{title,content}])
  this.setState({
    list:newArr
  })
}
   //删除
   del=(index)=>{
      this.state.list.splice(index,1)
      this.setState({
        list:this.state.list
      })
   } 

render() {
  return (
      <>
        <div className="warpper">
          <div className="com">
            <input type="text" placeholder="请输入评论人" className="cominput" onChange={this.updateTitle}/>
            <textarea className="textarea" cols="30" rows="10" placeholder="请输入评论内容" onChange={this.updateContent}></textarea>
          </div>
          <button className="btn" onClick={this.comments}>发表评论</button>
          <div className="combottom">
            <ul>
              {
                this.state.list.map((item,index)=> 
                   <li key={index} className="li">
                      <div className="div">
                        <h2 className="h2">评论人：{item.title}</h2>
                        <span className="p">评论内容：{item.content}</span>
                      </div>
                      <span onClick={this.del}>X</span>
                   </li>
                )
              }
            </ul>
          </div>
        </div>
      </>
    )
  }
}
export default DemoComment;
